package org.tis.tools.abf.module.ac.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tis.tools.abf.module.ac.controller.request.AcMenuFilterRequest;
import org.tis.tools.abf.module.ac.dao.AcMenuMapper;
import org.tis.tools.abf.module.ac.entity.AcApp;
import org.tis.tools.abf.module.ac.entity.AcFunc;
import org.tis.tools.abf.module.ac.entity.AcMenu;
import org.tis.tools.abf.module.ac.entity.vo.AcMenuApiDetail;
import org.tis.tools.abf.module.ac.entity.vo.AcMenuDetail;
import org.tis.tools.abf.module.ac.entity.vo.AcMenuUiEntityDetail;
import org.tis.tools.abf.module.ac.exception.AcExceptionCodes;
import org.tis.tools.abf.module.ac.exception.AcMenuManagementException;
import org.tis.tools.abf.module.ac.service.IAcAppService;
import org.tis.tools.abf.module.ac.service.IAcFuncService;
import org.tis.tools.abf.module.ac.service.IAcMenuService;
import org.tis.tools.abf.module.common.entity.enums.YON;
import org.tis.tools.core.utils.StringUtil;
import org.tis.tools.model.exception.i18.ExceptionCodes;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static org.tis.tools.core.utils.BasicUtil.wrap;

/**
 * acMenu的Service接口实现类
 *
 * @author Auto Generate Tools
 * @date 2018/04/23
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AcMenuServiceImpl extends ServiceImpl<AcMenuMapper, AcMenu> implements IAcMenuService {

    @Autowired
    private IAcAppService iAcAppService;
    @Autowired
    IAcMenuService acMenuService;
    @Autowired
    IAcFuncService acFuncService;

    /**
     * 重新排序： 自增
     */
    private static final String REORDER_AUTO_PLUS = "plus";
    /**
     * 重新排序： 自减
     */
    private static final String REORDER_AUTO_MINUS = "minus";


    /**
     * 根据父菜单查询出子菜单
     */
    @Override
    public List<AcMenuUiEntityDetail> selectSubMenu(String gidParents) throws AcMenuManagementException {

        if (StringUtil.isEmpty(gidParents)) {
            throw new AcMenuManagementException(ExceptionCodes.LACK_PARAMETERS_WHEN_QUERY, wrap("GUID", "AC_MENU"));
        }

        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq(AcMenu.COLUMN_GUID_PARENTS, gidParents);

        List<AcMenu> lists = selectList(wrapper);
        List<AcMenuUiEntityDetail> menuUiEntityDetailList = getUiEntity(lists);
        return menuUiEntityDetailList;
    }

    /**
     * 根据 id,和name 条件，查询该菜单的下一级所有的子菜单
     */
    @Override
    public List<AcMenuUiEntityDetail> getSubMenuFilter(String guidParents, String name) throws AcMenuManagementException {

        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq(AcMenu.COLUMN_GUID_PARENTS, guidParents);
        if (StringUtil.isNotEmpty(name)){
            wrapper.like(AcMenu.COLUMN_MENU_NAME,name);
        }

        List<AcMenu> lists = selectList(wrapper);
        List<AcMenuUiEntityDetail> menuUiEntityDetailList = getUiEntity(lists);
        return menuUiEntityDetailList;
    }

    /**
     * 菜单移动
     */
    @Override
    public AcMenu moveMenu(String targetGuid, String moveGuid, BigDecimal order) throws AcMenuManagementException {

        // 查询移动的菜单信息及其下属的所有菜单信息
        AcMenu moveMenu = acMenuService.selectById(moveGuid);
        if (moveMenu == null) {
            throw new AcMenuManagementException(ExceptionCodes.NOT_FOUND_WHEN_QUERY,
                    wrap("GUID '" + moveGuid + "' ", "AC_MENU"));
        }

        List<AcMenu> childMenus = acMenuService.selectList(new EntityWrapper<AcMenu>().like(AcMenu.COLUMN_MENU_SEQ, moveGuid));
        // 目标菜单节点
        AcMenu goalMenu = acMenuService.selectById(targetGuid);
        if (goalMenu == null) {
            throw new AcMenuManagementException(ExceptionCodes.NOT_FOUND_WHEN_QUERY,
                    wrap("GUID '" + targetGuid + "' ", "AC_MENU"));
        }

        // 源菜单节点
         // 源菜单GUID
        String sourceGuid = moveMenu.getGuidParents();
        // 源菜单显示顺序
        BigDecimal sourceOrder = moveMenu.getDisplayOrder();
        String sourceSeq = moveMenu.getMenuSeq();

        // 处理移动菜单信息
        // 改变父菜单信息
        moveMenu.setGuidParents(targetGuid);
        // 改变序列
        moveMenu.setMenuSeq(goalMenu.getMenuSeq() + "." + moveGuid);
        // 改变显示顺序
        moveMenu.setDisplayOrder(order);

        // 重新排序源菜单下的子菜单自减
        this.baseMapper.reorderMenu(sourceGuid, sourceOrder, REORDER_AUTO_MINUS);
        // 重新排序目标菜单下的子菜单自增
        this.baseMapper.reorderMenu(targetGuid, order,REORDER_AUTO_PLUS);
        // 更改移动的重组菜单信息
        acMenuService.updateById(moveMenu);
        // 如果改变了父节点需要同步改变子节点
        if (!StringUtils.equals(moveMenu.getGuidParents(), targetGuid)) {
            // 更改移动菜单下的子菜单
            for (AcMenu childMenu : childMenus) {
                // 排除当前移动菜单
                if (!StringUtils.equals(childMenu.getGuid(), moveGuid)) {
                    // 更新菜单序列
                    // update 表名 set 字段名=REPLACE (字段名,'原来的值','要修改的值')
                    String seq = childMenu.getMenuSeq();
                    AcMenu acMenu = new AcMenu();
                    acMenu.setGuid(childMenu.getGuid());
                    acMenu.setMenuSeq(seq.replace(sourceSeq, moveMenu.getMenuSeq()));
                    acMenuService.updateById(acMenu);
                }
            }
        }

        return moveMenu;
    }


    /**
     * 删除父菜单及其子菜单
     */
    @Override
    public AcMenu deleteAllSubAcMenu(String menuGuid) throws AcMenuManagementException {
        if (StringUtil.isEmpty(menuGuid)) {
            throw new AcMenuManagementException(ExceptionCodes.LACK_PARAMETERS_WHEN_QUERY, wrap("ID不能为空"));
        }
        /*查询对应菜单是否存在*/
        AcMenu acMenu = acMenuService.selectById(menuGuid);
        if (acMenu == null) {
            throw new AcMenuManagementException(ExceptionCodes.NOT_FOUND_WHEN_QUERY, wrap("找不到对应记录或已经被删除"));
        }
        /*查询子菜单，一并删除*/
        List<AcMenuUiEntityDetail> menuList = acMenuService.selectSubMenu(menuGuid);
        String parentGuid = "";
        BigDecimal index = new BigDecimal("0");
        parentGuid = acMenu.getGuidParents();
        index = acMenu.getDisplayOrder();
        boolean result = false;
        List<String> guidList = new ArrayList<>(menuList.size());
        for (AcMenuUiEntityDetail menu : menuList) {
            if (null != menu){
                guidList.add(menu.getGuid());
            }
        }
        if (guidList.size() > 0) {
            result = acMenuService.deleteBatchIds(guidList);
            // 其余兄弟菜单重新排序
            this.baseMapper.reorderMenu(parentGuid,index,REORDER_AUTO_MINUS);
        }
        result = acMenuService.delete(new EntityWrapper<AcMenu>().eq(AcMenu.COLUMN_GUID,acMenu.getGuid()));
        return acMenu;
    }

    /**
     * 修改菜单
     */
    @Override
    public AcMenu updateAcMenu(AcMenu acMenu) throws AcMenuManagementException {
        if (null == acMenu) {
            throw new AcMenuManagementException(AcExceptionCodes.OBJECT_IS_NULL, wrap("acMenu"));
        }
        if (StringUtil.isEmpty(acMenu.getGuid())) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("GUID"));
        }
        AcMenu menu = acMenuService.selectById(acMenu.getGuid());
        if (menu == null) {
            throw new AcMenuManagementException(ExceptionCodes.NOT_FOUND_WHEN_QUERY, wrap(acMenu.getGuid(), "AC_MENU"));
        }
        if (StringUtil.isEmpty(acMenu.getMenuName())) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("MENU_NAME"));
        }
//        if (StringUtil.isEmpty(acMenu.getMenuLabel())) {
//            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("MENU_LABLE"));
//        }
        if (StringUtil.isEmpty(acMenu.getMenuCode())) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("MENU_CODE"));
        }
        if (acMenu.getIsleaf() == null) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("ISLEAF"));
        }
        // 如果是叶子菜单，功能GUID不能为空
        if (acMenu.getIsleaf().equals(YON.YES)) {
            if (StringUtil.isEmpty(acMenu.getGuidFunc())) {
                throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("GUID_FUNC"));
            }
        }
        // 如果为根菜单
        if(StringUtil.isEquals(acMenu.getGuid(), menu.getGuidRoot())) {
            acMenu.setGuidParents(null);
            acMenu.setMenuSeq(menu.getGuid());
        } else {
            acMenu.setGuidParents(menu.getGuidParents());
            AcMenu acMenuParent = selectById(menu.getGuidParents());
            if (null == acMenuParent){
                throw new AcMenuManagementException(AcExceptionCodes.FAILURE_WHEN_QUERY_AC_MENU_PARENT,wrap("查询菜单的父菜单失败"));
            }else {
                acMenu.setMenuSeq(acMenuParent.getMenuSeq()+"."+menu.getGuid());
            }
        }

        menu.setMenuName(acMenu.getMenuName());
        menu.setMenuLabel(acMenu.getMenuLabel());
        menu.setMenuCode(acMenu.getMenuCode());
        menu.setGuidFunc(acMenu.getGuidFunc());

//        acMenu.setGuidApp(menu.getGuidApp());
//        acMenu.setGuidRoot(menu.getGuidRoot());
        acMenuService.updateAllColumnById(menu);
        return menu;
    }

    /**
     * 新增子菜单
     */
    @Override
    public AcMenu createChildMenu(AcMenu acMenu) throws AcMenuManagementException {
        if (null == acMenu) {
            throw new AcMenuManagementException(AcExceptionCodes.OBJECT_IS_NULL, wrap("AcMenu"));
        }
        // 校验传入参数 菜单名称 菜单显示名称 菜单代码  是否叶子菜单  应用GUID 父菜单GUID
        if (StringUtil.isEmpty(acMenu.getGuidApp())) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("GUID_APP"));
        }
        if (StringUtil.isEmpty(acMenu.getMenuName())) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("MENU_NAME"));
        }
//        if (StringUtil.isEmpty(acMenu.getMenuLabel())) {
//            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("MENU_LABLE"));
//        }
        if (StringUtil.isEmpty(acMenu.getMenuCode())) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("MENU_CODE"));
        }
        if (null == acMenu.getIsleaf()) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("ISLEAF"));
        }
        if (StringUtil.isEmpty(acMenu.getGuidParents())) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("GUID_PARENTS"));
        }
        // 如果是叶子菜单，功能GUID不能为空
        if (acMenu.getIsleaf().equals(YON.YES)) {
            if (null == acMenu.getIsleaf()) {
                throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("GUID_FUNC"));
            }
        }
        AcMenu parMenu = acMenuService.selectById(acMenu.getGuidParents());
        /** 查询是否存在父菜单 */
        if (parMenu == null) {
            throw new AcMenuManagementException(AcExceptionCodes.MENU_NOT_EXIST_BY_GUID
                    , wrap(acMenu.getGuidParents()));
        }
        /** 添加菜单GUID和序列*/
        acMenu.setGuidRoot(parMenu.getGuidRoot());
        acMenu.setDisplayOrder(new BigDecimal(acMenuService.selectCount(new EntityWrapper<AcMenu>().eq(AcMenu.COLUMN_GUID_PARENTS, acMenu.getGuidParents()))));

        //根据appGuid查询应用名称
        AcApp acApp = iAcAppService.selectById(acMenu.getGuidApp());
        if (null != acApp){
            acMenu.setMenuSeq(parMenu.getMenuSeq()+"."+acMenu.getGuid());
        }else {
            throw new AcMenuManagementException(AcExceptionCodes.FAILURE_WHRN_QUERY_AC_APP,wrap
                    ("应用id对应的应用不存在或已删除"));
        }
        acMenuService.insert(acMenu);

        acMenu.setGuidRoot(parMenu.getGuidRoot());
        acMenu.setMenuSeq(parMenu.getMenuSeq()+"."+acMenu.getGuid());
        updateAllColumnById(acMenu);
        return acMenu;
    }

    /**
     * 新增根菜单
     */
    @Override
    public AcMenu createRootMenu(AcMenu acMenu) throws AcMenuManagementException {
        if (null == acMenu) {
            throw new AcMenuManagementException(AcExceptionCodes.OBJECT_IS_NULL);
        }
        // 校验传入参数 菜单名称 菜单显示名称 菜单代码  是否叶子菜单  应用GUID
        if (StringUtil.isEmpty(acMenu.getGuidApp())) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY);
        }
        if (StringUtil.isEmpty(acMenu.getMenuName())) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY);
        }
//        if (StringUtil.isEmpty(acMenu.getMenuLabel())) {
//            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY);
//        }
        if (StringUtil.isEmpty(acMenu.getMenuCode())) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY);
        }
        List<AcMenuUiEntityDetail> acMenus = queryRootMenu(acMenu.getGuidApp());
        if (acMenus.size() > 0) {
            throw new AcMenuManagementException(AcExceptionCodes.CURRENT_APP_ALREADY_HAVE_ROOT_MENU);
        }
        //根据appGuid查询应用名称
        AcApp acApp = iAcAppService.selectById(acMenu.getGuidApp());
        if (null == acApp){
            throw new AcMenuManagementException(AcExceptionCodes.FAILURE_WHRN_QUERY_AC_APP,wrap("应用id对应的应用不存在或已删除"));
        }
        acMenu.setMenuSeq("000");
        acMenu.setGuidParents(null);
        acMenu.setIsleaf(YON.NO);
        acMenu.setDisplayOrder(new BigDecimal("0"));
        acMenuService.insert(acMenu);
        acMenu.setGuidRoot(acMenu.getGuid());
        acMenu.setMenuSeq(acMenu.getGuid());
        updateAllColumnById(acMenu);
        return acMenu;
    }

    /**
     * 查询应用下根菜单
     */
    @Override
    public List<AcMenuUiEntityDetail> queryRootMenu(String GUID_APP) throws AcMenuManagementException {
        // 校验传入参数
        if (StringUtil.isEmpty(GUID_APP)) {
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("GUID_APP"));
        }
        //查询应用下父节点字段为空的菜单，即为根菜单
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq(AcMenu.COLUMN_GUID_APP,GUID_APP);
        wrapper.isNull(AcMenu.COLUMN_GUID_PARENTS);

        List<AcMenu> lists = selectList(wrapper);
        List<AcMenuUiEntityDetail> menuUiEntityDetailList = getUiEntity(lists);

        return menuUiEntityDetailList;
    }

    /**
     * 过滤查询应用下菜单数据
     */
    @Override
    public AcMenuDetail queryAcMenuFilterLists(AcMenuFilterRequest acMenuFilterRequest) throws AcMenuManagementException {

        AcMenuDetail detailExit = null;

        if (StringUtil.isEmpty(acMenuFilterRequest.getMenuName())){
            //过滤条件为空,查询应用下的所有数据
            Wrapper<AcMenu> wrapper = new EntityWrapper<>();
            wrapper.eq(AcMenu.COLUMN_GUID_APP,acMenuFilterRequest.getGuidApp());
            wrapper.orderBy(AcMenu.COLUMN_DISPLAY_ORDER,true);

            List<AcMenu> menuList = new LinkedList<>();
            menuList = selectList(wrapper);
            if (0 != menuList.size()){
                //查询结果非空,则循环拼接
                List<AcMenuUiEntityDetail> menuUiEntityDetailList = getUiEntity(menuList);
                detailExit = setInAcMenuDetail(menuUiEntityDetailList);
            }
        }else {
            //如果有 过滤name条件查询
            Wrapper<AcMenu> wrapper = new EntityWrapper<>();
            wrapper.eq(AcMenu.COLUMN_GUID_APP,acMenuFilterRequest.getGuidApp());
            wrapper.like(AcMenu.COLUMN_MENU_NAME,acMenuFilterRequest.getMenuName());
            wrapper.orderBy(AcMenu.COLUMN_DISPLAY_ORDER,true);
            List<AcMenu> menuList = new LinkedList<>();
            menuList = selectList(wrapper);

            //如果有 过滤lable条件查询
            Wrapper<AcMenu> lableWrapper = new EntityWrapper<>();
            lableWrapper.eq(AcMenu.COLUMN_GUID_APP,acMenuFilterRequest.getGuidApp());
            lableWrapper.like(AcMenu.COLUMN_MENU_LABEL,acMenuFilterRequest.getMenuName());
            lableWrapper.orderBy(AcMenu.COLUMN_DISPLAY_ORDER,true);
            List<AcMenu> menuLableList = new LinkedList<>();
            menuLableList = selectList(lableWrapper);

            //去重
            menuList.addAll(menuLableList);
            Set menuSet = new LinkedHashSet(menuList.size());
            menuSet.addAll(menuList);
            menuList.clear();
            menuList.addAll(menuSet);

            //所有对象
            Wrapper<AcMenu> menuWrapper = new EntityWrapper<>();
            menuWrapper.eq(AcMenu.COLUMN_GUID_APP,acMenuFilterRequest.getGuidApp());
            menuWrapper.orderBy(AcMenu.COLUMN_DISPLAY_ORDER,true);
            List<AcMenu> allMenuList = new LinkedList<>();
            allMenuList = selectList(menuWrapper);

            Map<String,AcMenu> allMap = new LinkedHashMap<>();
            if (0 != allMenuList.size()){
                //查询结果非空,则循环拼接
                for (AcMenu acMenu : allMenuList){
                    if (null != acMenu){
                        allMap.put(acMenu.getGuid(),acMenu);
                    }
                }
            }
            //找出所有需要排序的节点信息
            List<AcMenu> resultList = new LinkedList<>();
            if (0 != menuList.size()){
                for (int i = 0; i < menuList.size(); i++){
                    if (null != menuList.get(i).getGuidParents()){
                        AcMenu  acMenuSon = menuList.get(i);
                        resultList.add(acMenuSon);
                        AcMenu acMenuFather = acMenuSon;
                        while(null != allMap.get(acMenuSon.getGuidParents()).getGuidParents()) {
                            acMenuFather = allMap.get(acMenuSon.getGuidParents());
                            resultList.add(acMenuFather);
                            acMenuSon = acMenuFather;
                        }
                        resultList.add(allMap.get(acMenuFather.getGuidParents()));
                    }
                }

                if (0 != menuList.size()){
                    //查询结果非空,则循环拼接
                    List<AcMenuUiEntityDetail> menuUiEntityDetailList = getUiEntity(menuList);
                    detailExit = setInAcMenuDetail(menuUiEntityDetailList);
                }
            }
        }
        return detailExit;
    }

    private AcMenuDetail setInAcMenuDetail(List<AcMenuUiEntityDetail> resultList){

        AcMenuDetail detailExit = null;

        Map<String,AcMenuDetail> map = new LinkedHashMap<>();
        for (AcMenuUiEntityDetail acMenu : resultList){
            if (null != acMenu){
                map.put(acMenu.getGuid(),new AcMenuDetail(acMenu,new ArrayList<>()));
            }
        }

        for(String key:map.keySet())
        {
            if (null != map.get(map.get(key).getGuidParents())){
                map.get(map.get(key).getGuidParents()).getChildren().add(map.get(map.get(key).getGuid()));
            }else {
                detailExit = map.get(map.get(key).getGuid());
            }
        }

        return detailExit;
    }

    private List<AcMenuDetail> setMenuTree(List<AcMenuDetail> sonList){

        List<AcMenuDetail> detailList = new ArrayList<>();

        List<String> parentGuidList = new ArrayList<>();

        for (AcMenuDetail acMenuDetail : sonList){
            if (null != acMenuDetail){
                if (null != acMenuDetail.getGuidParents()) {
                    parentGuidList.add(acMenuDetail.getGuidParents());
                }else {
                    detailList.add(acMenuDetail);
                }
            }
        }

        LinkedHashSet<String> set = new LinkedHashSet<>(parentGuidList.size());
        set.addAll(parentGuidList);
        parentGuidList.clear();
        parentGuidList.addAll(set);

        if (0 == parentGuidList.size()){
            if (1 != sonList.size()){
            }
            return sonList;
        }

        for (String parentGuid : parentGuidList){
            if (!StringUtil.isEmpty(parentGuid)){
                AcMenu acMenu = selectById(parentGuid);
                List<AcMenuDetail> sonAcMenu = new ArrayList<>();
                for (AcMenuDetail acMenuDetail : sonList){
                    if (null != acMenuDetail){
                        if (parentGuid.equals(acMenuDetail.getGuidParents())){
                            sonAcMenu.add(acMenuDetail);
                        }
                    }
                }
                if (0 != detailList.size()) {
                    List<AcMenuDetail> list = new ArrayList<>();
                    for (AcMenuDetail acMenuDetail : detailList) {
                        if (null != acMenuDetail) {
                            if (parentGuid.equals(acMenuDetail.getGuidParents())) {
                                sonAcMenu.add(acMenuDetail);
                                list.add(acMenuDetail);
                            }
                        }
                    }
                    //去掉重复的子分支数据
                    detailList.removeAll(list);
                }
                String uiEntity = "";
                if (StringUtil.isNotEmpty(acMenu.getGuidFunc())){
                    AcFunc acFunc = acFuncService.selectById(acMenu.getGuidFunc());
                    if (null != acFunc) {
                        uiEntity = acFunc.getUiEntry();
                    }
                }
                AcMenuUiEntityDetail acMenuUiEntityDetail = new AcMenuUiEntityDetail(acMenu,uiEntity);
                AcMenuDetail acMenuDetail = new AcMenuDetail(acMenuUiEntityDetail,sonAcMenu);
                detailList.add(acMenuDetail);
            }
        }
        return setMenuTree(detailList);
    }


    /**
     * 重新排序菜单下的子菜单
     */
    @Override
    public void reorderMenu(String identityGuid, BigDecimal index , String flag) {
        if(StringUtil.isEmpty(identityGuid)){
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("GUID"));
        }
        if(StringUtil.isEmpty(index.toString())){
            throw new AcMenuManagementException(AcExceptionCodes.PARMS_NOT_ALLOW_EMPTY, wrap("GUID"));
        }
        AcMenu acMenu = acMenuService.selectById(identityGuid);

        BigDecimal oreder = acMenu.getDisplayOrder();
        BigDecimal ore = new BigDecimal("1");
        if(null != oreder){
            if(flag.equals("plus")){
                oreder = oreder.add(ore);
            }else{
                oreder = oreder.subtract(ore);
            }
        }else {
            //当displayOrder字段为空时,他的处理逻辑是什么
        }
        acMenu.setDisplayOrder(oreder);
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq(AcMenu.COLUMN_GUID_PARENTS ,identityGuid)
                .where(AcMenu.COLUMN_GUID_PARENTS + " >= " + index);
        boolean result =  acMenuService.update(acMenu ,wrapper);
    }

    private List<AcMenuUiEntityDetail> getUiEntity(List<AcMenu> menuList){

        List<AcMenuUiEntityDetail> list = new ArrayList<>();

        if (0 == menuList.size()){
            return list;
        }

        for (AcMenu acMenu : menuList){
            if (null != acMenu){
                String uiEntity = "";
                String funcName = "";
                String serviceEntry = "";
                if (StringUtil.isNotEmpty(acMenu.getGuidFunc())){
                    AcFunc acFunc = acFuncService.selectById(acMenu.getGuidFunc());
                    uiEntity = acFunc.getUiEntry();
                    funcName = acFunc.getFuncName();
                    serviceEntry = acFunc.getServiceEntry();
                }

//                if (null == acMenu.getDisplayOrder() || -1 == acMenu.getDisplayOrder().intValue()){
//                    if (StringUtil.isEmpty(acMenu.getGuidParents())){
//                        Wrapper<AcMenu> wrapper = new EntityWrapper<>();
//                        wrapper.isNull(AcMenu.COLUMN_GUID_PARENTS);
//                        List<AcMenu> acMenuList = selectList(wrapper);
//                        acMenuList.remove(acMenu);
//                        if (0 == acMenuList.size()){
//                            acMenu.setDisplayOrder(new BigDecimal("0"));
//                        }else {
//
//                        }
//                    }else {
//                        acMenu.setDisplayOrder(new BigDecimal(acMenuService.selectCount(new EntityWrapper<AcMenu>().eq(AcMenu.COLUMN_GUID_PARENTS, acMenu.getGuidParents()))-1));
//                    }
//                    updateAllColumnById(acMenu);
//                }
                //如果某菜单的序列为-1时,处理disPlayOrder字段
                if (null == acMenu.getDisplayOrder() || -1 == acMenu.getDisplayOrder().intValue()){
                    List<AcMenu> acMenuList = new ArrayList<>();
                    if (StringUtil.isEmpty(acMenu.getGuidParents())){
                        Wrapper<AcMenu> wrapper = new EntityWrapper<>();
                        wrapper.isNull(AcMenu.COLUMN_GUID_PARENTS);
                        acMenuList = selectList(wrapper);
                        acMenuList.remove(acMenu);
                    }else {
                        Wrapper<AcMenu> wrapper = new EntityWrapper<>();
                        wrapper.eq(AcMenu.COLUMN_GUID_PARENTS,acMenu.getGuidParents());
                        acMenuList = selectList(wrapper);
                        acMenuList.remove(acMenu);
                    }
                    if (0 == acMenuList.size()){
                        acMenu.setDisplayOrder(new BigDecimal("0"));
                    }else {
                        for (int i = 0; i < acMenuList.size(); i++){
                            boolean existNum = true;
                            for (int j = 0; j < acMenuList.size(); j++){
                                if (i == acMenuList.get(j).getDisplayOrder().intValue()){
                                    existNum = false;
                                }
                            }
                            if (existNum){
                                acMenu.setDisplayOrder(new BigDecimal(i));
                                updateById(acMenu);
                                break;
                            }
                        }
                    }
                }
                list.add(new AcMenuUiEntityDetail(acMenu,uiEntity,funcName,serviceEntry));
            }
        }

        return list;
    }

    /**
     * 根据GUID查询菜单
     */
    @Override
    public AcMenuUiEntityDetail getDetail(String guid) throws AcMenuManagementException {

        AcMenu acMenu = selectById(guid);
        List<AcMenu> list = new ArrayList<>();
        list.add(acMenu);

        List<AcMenuUiEntityDetail> uiEntityDetailList = getUiEntity(list);
        return uiEntityDetailList.get(0);
    }

    /**
     * 分页查询菜单
     */
    @Override
    public Page<AcMenuUiEntityDetail> getPage(Page<AcMenu> page, EntityWrapper<AcMenu> wrapper) throws AcMenuManagementException {

        Page<AcMenu> menuPage = selectPage(page,wrapper);
        List<AcMenu> menuList = menuPage.getRecords();

        Page<AcMenuUiEntityDetail> uiEntityDetailPage = new Page<>();
        List<AcMenuUiEntityDetail> uiEntityDetailList = getUiEntity(menuList);

        uiEntityDetailPage.setRecords(uiEntityDetailList);
        uiEntityDetailPage.setCurrent(menuPage.getCurrent());
        uiEntityDetailPage.setSize(menuPage.getSize());
        uiEntityDetailPage.setTotal(menuPage.getTotal());

        return uiEntityDetailPage;
    }

    /**
     * 对外服务提供接口
     * 查询应用下的菜单
     */
    @Override
    public AcMenuApiDetail getMenusByApp(String appId) throws AcMenuManagementException {

        //过滤条件为空,查询应用下的所有数据
        Wrapper<AcMenu> wrapper = new EntityWrapper<>();
        wrapper.eq(AcMenu.COLUMN_GUID_APP,appId);
        wrapper.orderBy(AcMenu.COLUMN_DISPLAY_ORDER,true);

        List<AcMenu> menuList = selectList(wrapper);
        if (0 == menuList.size()){
            return null;
        }

        List<AcMenuApiDetail> list = setMenuApiDetail(menuList);
        return setInAcMenuApiDetail(list);
    }

    /**
     * 对外服务提供接口
     * 根据应用和操作员获取菜单
     *
     * @param appId      应用GUID
     * @param operatorId 操作员GUID
     * @return 应用菜单的树结构
     * @throws AcMenuManagementException 菜单异常处理
     */
    @Override
    public AcMenuApiDetail getMenusInAppOperator(String appId, String operatorId) throws AcMenuManagementException {

        /**获取应用下的菜单*/
        Wrapper<AcMenu> wrapper = new EntityWrapper<>();
        wrapper.eq(AcMenu.COLUMN_GUID_APP,appId);
        wrapper.orderBy(AcMenu.COLUMN_DISPLAY_ORDER,true);

        List<AcMenu> appMenuList = selectList(wrapper);

        /**获取操作员下菜单*/
        List<String> funcByOperators = this.baseMapper.getFuncByOperator(operatorId);
        List<String> funcNoCkeckInApp = this.baseMapper.getFuncNoCkeck(appId);
        funcByOperators.addAll(funcNoCkeckInApp);
        Wrapper<AcMenu> menuWrapper = new EntityWrapper<>();
        menuWrapper.in(AcMenu.COLUMN_GUID_FUNC,funcByOperators);
        menuWrapper.orderBy(AcMenu.COLUMN_DISPLAY_ORDER,true);

        List<AcMenu> operatorMenuList = selectList(menuWrapper);

        /** 得到上面两个集合的交集 */
        List<AcMenu> menuList = appMenuList.stream().filter(item -> operatorMenuList.contains(item) ).collect(Collectors.toList());

        if (0 == menuList.size()){
            return null;
        }

        Map<String,AcMenu> allMap = new LinkedHashMap<>();
        if (0 != appMenuList.size()){
            //查询结果非空,则循环拼接
            for (AcMenu acMenu : appMenuList){
                if (null != acMenu){
                    allMap.put(acMenu.getGuid(),acMenu);
                }
            }
        }
        //找出所有需要排序的节点信息
        List<AcMenu> resultList = new LinkedList<>();
        for (int i = 0; i < menuList.size(); i++){
            if (null != menuList.get(i).getGuidParents()){
                AcMenu  acMenuSon = menuList.get(i);
                resultList.add(acMenuSon);
                AcMenu acMenuFather = acMenuSon;
                while(null != allMap.get(acMenuSon.getGuidParents()).getGuidParents()) {
                    acMenuFather = allMap.get(acMenuSon.getGuidParents());
                    resultList.add(acMenuFather);
                    acMenuSon = acMenuFather;
                }
                resultList.add(allMap.get(acMenuFather.getGuidParents()));
            }
        }

//                //查询结果非空,则循环拼接
//                List<AcMenuUiEntityDetail> menuUiEntityDetailList = getUiEntity(menuList);
//                detailExit = setInAcMenuDetail(menuUiEntityDetailList);


        List<AcMenuApiDetail> list = setMenuApiDetail(resultList);
        return setInAcMenuApiDetail(list);
    }

    /**
     * 将AcMenu拼接为AcMenuApiDetail对象
     */
    private List<AcMenuApiDetail> setMenuApiDetail(List<AcMenu> menuList){

        if (0 == menuList.size()){
            return new ArrayList<>();
        }

        List<AcMenuApiDetail> list = new LinkedList<>();
        for (AcMenu acMenu : menuList){
            if (null != acMenu){
                AcMenuApiDetail acMenuApiDetail = new AcMenuApiDetail(acMenu,null);
                list.add(acMenuApiDetail);
            }
        }
        return list;
    }

    /**
     * 拼接对外服务的返回树结构
     */
    private AcMenuApiDetail setInAcMenuApiDetail(List<AcMenuApiDetail> resultList){

        if (0 == resultList.size()){
            return new AcMenuApiDetail();
        }

        AcMenuApiDetail detailExit = null;

        Map<String,AcMenuApiDetail> map = new LinkedHashMap<>();
        for (AcMenuApiDetail acMenuApiDetail : resultList){
            if (null != acMenuApiDetail){
                map.put(acMenuApiDetail.getGuid(),new AcMenuApiDetail(acMenuApiDetail,new ArrayList<>()));
            }
        }

        for(String key:map.keySet())
        {
            if (null != map.get(map.get(key).getGuidParents())){
                map.get(map.get(key).getGuidParents()).getChildren().add(map.get(map.get(key).getGuid()));
            }else {
                detailExit = map.get(map.get(key).getGuid());
            }
        }

        return detailExit;
    }
}

